from django.shortcuts import render
from django.views import View
import logging
from django.http import JsonResponse
from django.core.paginator import Paginator
from haystack.views import SearchView

from goods.models import GoodsCategory, SKU
from goods.utils import get_breadcrumb

# Create your views here.

# 创建日志生成器
logger = logging.getLogger('django')


class MySearchView(SearchView):
    def create_response(self):
        # 有漏洞
        # data = self.get_context()
        # # data['query']: 用户搜索词
        # # data['page']: django分页对象——当前页
        # # data['page'].object_list分页结果,是SearchResult对象；SearchResult.object属性是对应SKU对象
        # # data['paginator']: django分页器对象
        # data_list = []
        # for result in data['page'].object_list:
        #     data_list.append({
        #         'id': result.object.id,
        #         'name': result.object.name,
        #         'price': result.object.price,
        #         'default_image_url': result.object.default_image_url,
        #         'searchkey': data['query'],
        #         'page_size': data['paginator'].num_pages,
        #         'count': data['paginator'].count
        #     })
        #
        #     # 默认JsonResponse只能传入字典，如果传入列表必须设置safe=False
        #     return JsonResponse(data_list, safe=False)

# =========================================
        # page = self.request.GET.get('page')
        # 获取搜索结果
        context = self.get_context()
        data_list = []
        for sku in context['page'].object_list:
            data_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image_url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,   # 物品的分页的总页数
                'count': context['page'].paginator.count    # sku总个数
            })
        # 拼接参数, 返回
        return JsonResponse(data_list, safe=False)


class HotGoodsView(View):
    def get(self, request, category_id):
        try:
            skus = SKU.objects.filter(category_id=category_id,
                                      is_launched=True).order_by('-sales')[:2]
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '获取数据失败'})

        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id': sku.id,
                'default_image_url': sku.default_image_url,
                'name': sku.name,
                'price': sku.price
            })

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'hot_skus': hot_skus})


class ListView(View):
    def get(self, request, category_id):
        # 提取参数
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')

        # 获取三级菜单分类信息:
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '获取数据失败'})

        breadcrumb = get_breadcrumb(category)
        try:
            skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by(ordering)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '获取数据失败'})

        # 3.2 分页 —— page、page_size
        # Paginator(object_list, per_page): object_list是模型类查询集，per_page指每页几个

        paginator = Paginator(skus, page_size)
        # paginator.count属性，记录被分页数据的总数
        # paginator.num_pages属性，记录分到的总页数
        # paginator.per_page属性，记录是按照每页几个划分

        # page(number): number表示取第几页
        # 返回值是当前页对象
        try:
            page_skus = paginator.page(page)
            # page.object_list属性，记录当前页中的查询集
            # page.num属性，记录当前是第几页
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': 'page数据出错'})

        total_page = paginator.num_pages

        list = []
        for sku in page_skus:
            list.append({
                'id': sku.id,
                'default_image_url': sku.default_image_url,
                'name': sku.name,
                'price': sku.price
            })

        return JsonResponse({'code': 0, 'errmsg': 'ok',
                             'breadcrumb': breadcrumb,
                             'list': list,
                             'count': total_page})

